// dify知识库api
import { KeyEnum } from './apiKeys';
// dify知识库api
import difyInstance from './instance';

const AppOptions = import.meta.env;
const apiUrl = AppOptions.VITE_DIFY_IP;
// segment
// 添加数据段接口
const addSegment = (
  dataset_id: string,
  document_id: string,
  segments: Array<{ content: string }>,
) => {
  difyInstance.defaults.headers.common.Authorization = `Bearer ${KeyEnum.DATASET}`;

  return difyInstance.post(
    `${apiUrl}/datasets/${dataset_id}/documents/${document_id}/segments`,
    {
      segments,
    },
  );
};

// 更新数据段接口（有bug：第一次修改，不带keywords参数，改完片段就会变成错误状态；第一次如果带了，后面无论带不带，都没有问题）
const updateSegment = (
  dataset_id: string,
  document_id: string,
  segment_id: string,
  content: string,
) => {
  difyInstance.defaults.headers.common.Authorization = `Bearer ${KeyEnum.DATASET}`;
  return difyInstance.post(
    `${apiUrl}/datasets/${dataset_id}/documents/${document_id}/segments/${segment_id}`,
    {
      segment: {
        content,
      },
    },
  );
};

// 查询段落接口
const querySegments = (
  dataset_id: string,
  document_id: string,
  fileId: string,
) => {
  difyInstance.defaults.headers.common.Authorization = `Bearer ${KeyEnum.DATASET}`;

  const url = `${apiUrl}/datasets/${dataset_id}/documents/${document_id}/segments`;
  return difyInstance.get(url, {
    params: {
      keyword: fileId,
    },
  });
};

// 采用删除再添加代替更新
const deleteSegment = (
  dataset_id: string,
  document_id: string,
  segment_id: string,
) => {
  difyInstance.defaults.headers.common.Authorization = `Bearer ${KeyEnum.DATASET}`;
  return difyInstance.delete(
    `${apiUrl}/datasets/${dataset_id}/documents/${document_id}/segments/${segment_id}`,
  );
};

export default {
  addSegment,
  updateSegment,
  querySegments,
  deleteSegment,
};
